import React, {useEffect, useState} from 'react';
import {Avatar, Button, Col, Image, List, PageHeader, Row, Space, Input, message, Spin} from "antd";
import {
    LikeFilled,
    LikeOutlined,
    MessageOutlined,
    StarFilled,
    StarOutlined,
} from "@ant-design/icons";
import CommentList from "../../commentList/index";
import style from'./index.module.css'
import {get} from "../../../utils/get"
import ava from "../../../assets/img/i.png"
import {post} from "../../../utils/post";

const { TextArea } = Input;
/**
 * 推文详情页
 *
 */
const Type =['ISLIKE','ISFAVOR'];
function TweetDetail(props) {
    const [tweet,changeTweet]=useState({})  //推文数据
    const [comment,changeComment]=useState(""); //自己的评论
    const [otherComment,changeOtherComment]=useState([])//其他评论
    const [loading,setLoading]=useState(false)
    const{shareId} =props.match.params
    const userdata = JSON.parse(localStorage.getItem('USERDATA'))
    const imgSrc=userdata?(userdata.avatar?userdata.avatar:ava):ava
    const nickname1=userdata?userdata.nickname:"访客"
    const token = localStorage.getItem('TOKEN')
    //获得单条推文数据
    const getShareItem=async ()=>{
        setLoading(true)
        const res =await get(`/share/item?shareId=${shareId}`)
        if(res.data.code===0)
            changeTweet(res.data.data)
        setLoading(false)
    }
    useEffect(()=>{
        getShareItem()
    },[])
    //推文时间
    const myTime=(time)=>{
        return time?.substring(0,10)+" "+time?.substring(11,19);
    }
    //保存textArea 
    const handleChange=({ target: { value } })=>{
        changeComment(value)
    }
    const changeLikeOrFavor=async (tweet_id,isLike,type)=>{//处理点赞
        if(!token) return;
        if(type===Type[0]){//点赞
            if(!isLike){
                const res= await post(`/share/${tweet_id}/like`,{},token)
                if(res.data.code===0){
                    tweet.isLike=true;
                    tweet.likeCount++;
                    changeTweet({...tweet})
                }
                else{
                    message.error(res.data.errorMsg)
                }
            }else{//取消点赞
                const res= await post(`/share/${tweet_id}/unlike`,{},token)
                if(res.data.code===0) {
                    tweet.isLike=false;
                    tweet.likeCount--;
                    changeTweet({...tweet})
                }else message.error(res.data.errorMsg)
            }
        }
        else if(type===Type[1]){//收藏
            if(!isLike){
                const res=await post(`/share/${tweet_id}/favor`,{},token)
                if(res.data.code===0) {
                    tweet.isFavor = true;
                    tweet.favorCount++;
                    changeTweet({...tweet})
                }
                else message.error(res.data.errorMsg)
            }
            else{
                const res=await post(`/share/${tweet_id}/unFavor`,{},token)
                    if(res.data.code===0){
                        tweet.isFavor=false;
                        tweet.favorCount--;
                        changeTweet({...tweet})
                    }
                    else message.error(res.data.errorMsg)
            }
        }
    }
    const sendComment=async ()=>{//发送评论
        if(!token) {
            message.info('请登录后评论');
            changeComment("");
            return;
        }
        if(comment){//评论不为空
            const res=await post(`/share/${shareId}/comment`,{
                content:comment
            }, token)
            if(res.data.code === 0 ){
                changeComment("");
                message.success("发送成功");
                getShareItem()
            }else{
                message.error(res.data.errorMsg);
            }
        }else{
            message.warning('请输入一点东西吧~')
        }
    }
    const {avatar,commentCount,content,createTime,nickname,favorCount,likeCount,isFavor,isLike,images}=tweet;
    return (
        <div className={style.main}>
            <PageHeader
                onBack={() =>{props.history.goBack()}}
                title="分享"
                className={style.header}
            />
            <Spin tip={"浏览器又在开摆了，请稍后"} spinning={loading}>
            <List.Item className={`${style.bodyItem}`} key={shareId}>
            <List.Item.Meta className={`${style.meta}`}
                            avatar={<Avatar src={avatar} />}
                            title={<a style={{color:'#1890ff'}}>{nickname}</a>}
                            // onClick={()=>{props.history.push(`/index/${shareId}`)}}
            />
            <div className={style.content}>
                {content}
            </div>
            {/*图片*/}
            <Row>
                {
                    images!==undefined?images.map((value,key) => {
                        return(
                            <Col className="gutter-row" key={key} span={8}>
                                <Image
                                    className={`${style.img}`}
                                    key={key}
                                    width={160}
                                    height={160}
                                    alt="照片"
                                    src={value}
                                />
                            </Col>
                        )
                    }):""
                }
            </Row>
            <div className={style.dataBox}>
                {myTime(createTime)}
            </div>
                <div  className={style.dataBox}>
                    <span className={style.retweet}>{favorCount}</span>
                    <span className={style.retweetRight}>收藏</span>
                    <span className={style.retweet}>{commentCount}</span>
                    <span className={style.retweetRight}>评论</span>
                    <span className={style.retweet}>{likeCount}</span>
                    <span className={style.retweetRight}>点赞</span>
                </div>
                <div className={style.action}>
                    <Row>
                        <Col className="gutter-row" span={6} >
                            {
                                isFavor? (<StarFilled style={{color:'#ffd75a'}}
                                                      onClick={()=>changeLikeOrFavor(shareId,isFavor,Type[1])}/>)
                                    :(<StarOutlined onClick={()=>changeLikeOrFavor(shareId,isFavor,Type[1])}/>)
                            }
                            <span>{favorCount}</span>
                        </Col>
                        <Col className="gutter-row" span={6} >
                            {
                                isLike?(<LikeFilled style={{color:'#0170fe'}}
                                                    onClick={()=>changeLikeOrFavor(shareId,isLike,Type[0])}/>)
                                    :(<LikeOutlined onClick={()=>changeLikeOrFavor(shareId,isLike,Type[0])}/>)
                            }
                            <span>{likeCount}</span>
                        </Col>
                        <Col className="gutter-row"  span={6}>
                            <MessageOutlined/>
                            <span>{commentCount}</span>
                        </Col>
                    </Row>
                </div>
                <div>
                    <img src={imgSrc} className={style.avatar} alt="" />
                    <Button type={"primary"} disabled={token?false:true} shape="round" onClick={()=>sendComment()} className={style.postBtn}>
                        发送
                    </Button>
                    <TextArea
                        value={comment}
                        onChange={handleChange}
                        showCount
                        allowClear
                        maxLength={100}
                        placeholder="说点什么"
                        autoSize={{ minRows: 3, maxRows: 5 }}
                        style={{padding:'0  20px 0 15px'}}
                    />
                </div>
            </List.Item>
            </Spin>
            <CommentList shareId={shareId}/>
        </div>
    );
}

export default TweetDetail;
